<template>
  <div class="select-list">
    <template v-if="!is_info">
      <input type="hidden" :name="name" :value="modelValue">
      <div class="flex">
        <select_one v-show="select_config.length>1" class="mr-10" :config="select_config" v-model:value="model_name_now"></select_one>
        <el-button :disabled="!model_name_now" @click="selectListData()" type="primary">选择</el-button>
      </div>
    </template>
    <list class="select-list-data" :data="this_value" :cols="list_cols_now">
      <template v-slot:action="{row,index}">
        <el-button size="small" @click="move_up(row,index)" plain>上移</el-button>
        <el-button size="small" @click="remove_row(row,index)" type="danger" plain>移除</el-button>
      </template>
    </list>
  </div>
</template>

<script>
import Select_one from "@/components/auto_import/UnifyParam/select_one.vue";
import {decode_config, json_decode_object, json_encode} from "@/js/s94_tool.js";
import {getModelMap, iframe, msg} from "@/js/tool.js";

const action_col = {name:'action', label:'操作', type:'action', width:'120px', fixed:'right'}

export default {
  components: {Select_one},
  _title_: '选择数据列表',
  props: {
    name: [String, Number],
    modelValue: [Array, String],
    is_info: Boolean,
    limit_model_name: {
      type: [Array, String],
      _label_: '限制模型',
      _tip_: '允许选择的模型名称，多个逗号或者换行分隔，默认为全部',
      _inputType_: 'text_more'
    },
    max: [String, Number],
    unique_key: {
      type: String,
      default: 'id',
    }
  },
  emits: ['update:modelValue', 'change'],
  data(){

    let list_cols_def = [
      {name:'id', label:'ID', width:'60px'},
      {name:'head_img', label:'头图', width:'60px', type:'file_img'},
      {name:'title', label:'标题'},
      action_col,
    ]

    return {
      need_display: true,
      this_value: [],

      select_config: [],
      list_cols_def,
      list_cols_now: list_cols_def,
      model_name_now: '',
    }
  },
  methods: {
    modelValue_Handle(){
      if (typeof this.modelValue === 'string'){
        this.this_value = Object.values(json_decode_object(this.modelValue))
      }else {
        this.this_value = this.modelValue;
      }
    },
    limit_model_name_handle(){
      let limit = this.limit_model_name || [];
      if (limit && typeof limit === 'string') limit = limit.split(/\s*(\r?\n|,)\s*/).filter(v=>!!v);
      let res = [];
      Object.values(getModelMap()).forEach(model=>{
        if (limit.length && !~limit.indexOf(model.name)) return;
        res.push({
          content: model.label,
          value: model.name,
        })
      })
      if (res.length) this.model_name_now = res[0].value;
      this.select_config = decode_config(res);
    },
    update_value(v){
      if (typeof this.modelValue === 'string'){
        v = json_encode(v);
      }
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:modelValue', v);
      this.$emit('change', v);
    },

    async selectListData(){
      let path = `/model_v2_base/index?model_name=${this.model_name_now}`;
      iframe({
        href: path,
        btns: {
          '确定_primary': (win_app)=>{
            // 处理list的cols
            let list_url = typeof win_app.get_list_url === 'function' ? win_app.get_list_url() : win_app.$refs?.list_url;
            let list_cols = list_url?.config?.list_cols;
            if (list_cols){
              let list_cols_now = [];
              Object.values(list_cols).forEach(row=>{
                if (~['tenant_id','action'].indexOf(row.name)) return;
                list_cols_now.push(row);
              })
              list_cols_now.push(action_col);
              this.list_cols_now = list_cols_now;
            }
            // 选择的数据处理
            let selected = list_url?.selected || [];
            let max = Number(this.max) || 0;
            let unique_list = [];
            let push_list = [];
            this.this_value.forEach(v=>{
              unique_list.push(v[this.unique_key])
            })
            Object.values(selected).forEach(v=>{
              if (~unique_list.indexOf(v[this.unique_key])) return;
              unique_list.push(v[this.unique_key]);
              push_list.push(v);
            })
            if (max && max < this.this_value.length+push_list.length) return msg.fail(`最多选择${max}个`);
            this.this_value.push(...push_list);

            this.update_value(this.this_value);

            win_app.__iframe.show = false;
          }
        }
      })
    },
    remove_row(row, index){
      this.this_value.splice(index, 1);
      this.update_value(this.this_value);
    },
    move_up(row, index){
      if (index <= 0) return msg.fail('已经是第一个了，不能上移');
      const item = this.this_value.splice(index, 1)[0]; // 删除原位置的元素
      this.this_value.splice(index - 1, 0, item); // 插入到前一位
      this.update_value(this.this_value);
    },
  },
  watch: {
    modelValue(){
      if (!this.need_display) return;
      this.modelValue_Handle();
    },
    limit_model_name(){
      this.limit_model_name_handle()
    },
    model_name_now(){
      this.list_cols_now = this.list_cols_def;
    }
  },
  computed: {
  },
  mounted() {
    this.modelValue_Handle();
    this.limit_model_name_handle();
  }
}
</script>

<style scoped>
.mr-10{margin-right: 10px;}
</style>